# app/models/server_member.py
from app import db
from datetime import datetime
from sqlalchemy import Enum, CheckConstraint

class ServerMember(db.Model):
    __tablename__ = 'server_members'
    __table_args__ = (
        # 确保用户类型必填其一
        CheckConstraint(
            '(user_id IS NOT NULL AND guest_id IS NULL) OR '
            '(user_id IS NULL AND guest_id IS NOT NULL)',
            name='chk_member_type'
        ),
    )

    membership_id = db.Column(db.String(36), primary_key=True)
    server_id = db.Column(db.String(36), db.ForeignKey('servers.server_id'), nullable=False)
    user_id = db.Column(db.String(36), db.ForeignKey('users.user_id'))
    guest_id = db.Column(db.String(36), db.ForeignKey('guest_users.guest_id'))
    actChannel = db.Column(db.String(36))
    role = db.Column(Enum('admin', 'owner', 'member', name='member_roles'), default='member')
    joined_at = db.Column(db.DateTime, default=datetime.utcnow)
    can_leave = db.Column(db.Boolean, default=True)

    server = db.relationship('Server', back_populates='members')
    user = db.relationship('User', back_populates='memberships')
    guest = db.relationship('GuestUser', back_populates='memberships')
    channel_permissions = db.relationship('ChannelPermission', back_populates='member', cascade='all, delete-orphan')

    # 获取成员对象
    def get_member_object(self):
        return self.user if self.user_id else self.guest

    def __repr__(self):
        identifier = self.user.username if self.user else f'Guest#{self.guest_id[:6]}'
        return f'<ServerMember {identifier} in {self.server.name}>'